package practise.mulitThreads.ConcurrentInPractice.secondTime.Memorizer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by Richard on 7/28/2014.
 */
public class Memorizer {
    private Map<ComputerObject, Future<ComputeResult>> results = new ConcurrentHashMap<>();
    public void put(final ComputerObject computerObject){
        ComputerObject inner = computerObject;
        Callable<ComputeResult> task = new Callable<ComputeResult>() {
            @Override
            public ComputeResult call() throws Exception {
               Thread.sleep(1000);//simulate the thinking time
                return computerObject.getCalculator().visit();
            }
        };
        FutureTask<ComputeResult> futureTask = new FutureTask<>(task);
        results.putIfAbsent(computerObject,futureTask);
        new Thread(futureTask).start();

    }

    public ComputeResult get(ComputerObject computerObject){
        Future<ComputeResult> task = results.get(computerObject);
        if(task.isCancelled()){
            results.remove(computerObject);
        }
        else{
            if(task.isDone()){
                try {
                    return task.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
